package main

import (
	// For init func in bootstrap package.
	_ "com.opennews.openplatform/web_api/bootstrap"

	"com.opennews.openplatform/web_api/controllers"
	"com.opennews.openplatform/web_api/shared"
	"github.com/gin-gonic/gin"
	"io"
	"os"
)

// Uses gin in main & controller functions only. Because controller is tightly coupled with web framework, here is Gin.
// If we have to switch the framework the main function and controller should be the only place we have to refactor.
// For example, if we use gin.H everywhere that means we have more work to do during such refactoring.
func main() {
	setupLogger()

	// Default returns an Engine instance with the Logger and Recovery middleware already attached.
	router := gin.Default()

	// Uses middleware to check on access permission.
	router.Use(controllers.CheckAccessPermission)

	// Generates all controller routes.
	controllers.GenerateRoutes(router)

	// listens and serves on 0.0.0.0:8080 (for windows "localhost:8080")
	router.Run(":" + shared.ConfigService.GetAppConfig().Server.Port)
}

// Sets system level logger.
func setupLogger() {
	// Logging to file.
	f, _ := os.Create("output.log")

	// Writes the logs to file and console at the same time.
	// Uses functions in log package to log anything you need. Just like log.Println().
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
}

//func setupCustomRecovery(router *gin.Engine) {
//	// Recovery middleware recovers from any panics and writes a 500 if there was one.
//	router.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
//		if err, ok := recovered.(string); ok {
//			c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
//		}
//
//		c.AbortWithStatus(http.StatusInternalServerError)
//	}))
//}
